/*
 * $Id: MplString.java,v 1.2 2008/07/10 06:52:05 quy Exp $
 * Copyright(c) 2007-2010 makepolo.com, All Rights Reserved.
 */
package com.util;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Random;

/**
 * �ַ�����
 * @author xied
 * @version 1.0 2007-11-12
 * @since 1.0
 */
public final class MyString {
	/** �������� */
	private static final Random random = new Random();
	/** ��������ĸ�ֵ� */
	private static final char[] LETTER_AND_DIGIT = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
	/** ��������ĸ�ֵ䳤�� */
	private static final int LETTER_AND_DIGIT_LENGTH = LETTER_AND_DIGIT.length;
	
	/**
	 * ���캯��(��)
	 */
	private MyString() {}
	
	/**
	 * ����ַ��Ƿ�Ϊ���ַ�
	 * @param input �����ַ�
	 * @return
	 * <li>true���ַ�Ϊ��</li>
	 * <li>false���ַ�Ϊ��</li>
	 */
	public static boolean isEmpty(String input) {
		if (input == null) return true;
		return (input.trim().length() == 0);
	}
	
	/**
	 * ������ת��Ϊ�ַ����
	 * @param input ��ȡ�ö���
	 * @return ȡ�õ��ַ����
	 * @see #getString(Object, String)
	 */
	public static String getString(Object input) {
		return getString(input, "");
	}
	
	/**
	 * ������ת��Ϊ�ַ����
	 * @param input ��ȡ�ö���
	 * @param defVal ����Ϊ��ʱ��Ĭ�Ϸ���ֵ
	 * @return ȡ�õ��ַ����
	 */
	public static String getString(Object input, String defVal) {
		if (input == null) return defVal;
		String str = input.toString();
		return (str == null) ? defVal : str.trim();
	}
	
	/**
	 * �滻�ַ��е�ָ���ַ�
	 * @param input ���滻�ַ�
	 * @param oldChar ���滻�ַ�
	 * @param newChar �滻���ַ�
	 * @return
	 * <li>���滻�ַ�Ϊnull�򳤶�Ϊ��ʱ�����ش��滻�ַ�</li>
	 * <li>������滻����</li>
	 */
	public static String replaceAll(String input, char oldChar, char newChar) {
		if (input == null) return input;
		int len = input.length();
		if (input.length() == 0) return input;
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char ch = input.charAt(i);
			if (ch == oldChar) ch = newChar;
			sb.append(ch);
		}
		return sb.toString();
	}
	
	/**
	 * ȡ�������
	 * @param len ������
	 * @return ��ɵ������
	 */
	public static String getRandomString(final int len) {
		if (len < 1) return "";
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			sb.append(LETTER_AND_DIGIT[random.nextInt(LETTER_AND_DIGIT_LENGTH)]);
		}
		return sb.toString();
	}
	
	public static String urlEncode(String s) {
		try {
			String s1 = URLEncoder.encode(s, "gb2312");
			return s1;
		} catch (Exception ex) {
			return s;
		}
	}
	
	public static String urlDecode(String s) {
		try {
			String s1 = URLDecoder.decode(s, "gb2312");
			return s1;
		} catch (Exception ex) {
			return s;
		}
	}

}
